package serverService;

import java.util.*;
import java.util.logging.Logger;

import domain.*;

public class Matcher extends Thread {
	static Logger logger = Logger.getLogger(Matcher.class.getName());
	OrderQueue<Order> ordQ = new OrderQueue<Order>();
	private boolean isClosed = false;
	public void setClosed(boolean isClosed) {
		this.isClosed = isClosed;
	}

	private static Matcher instance = new Matcher();
	Map<Stock, OrderBook> mapOfStocks = new HashMap<Stock, OrderBook>();

	public Matcher() {
		for (Stock stock : Stock.values()) {
			OrderBook ob1 = new OrderBook();
			mapOfStocks.put(stock, ob1);
		}

		Thread thread = new Thread(this);
		thread.start();

		this.start();
	}

	public static Matcher getMatcher() {
		return instance;
	}

	public void addOrder(Order order) {
		ordQ.addEmail(order);
	}

	public void run() {
		System.out.println("MATCHER STARTED");
		while (!isClosed) {
			Order ord;

			ord = ordQ.getEmail();
			
			System.out.println("Order geted :"+ ord.getType());

			switch (ord.getType()) {
			case SELL:
				AddSeller(ord);
				break;
			case BUY:
				AddBuyer(ord);
			default:
				break;
			}
		}

	}

	public void AddSeller(Order order) {
		MatchResult result = mapOfStocks.get(order.getStock()).addSeller(order);
		if (result.getMatched()) {
			result.getSellerOrder().setClosedAmount(
					result.getSellerOrder().getAmount());
			sendToClients(result);
		}
		logger.info("Seller Added " + order.getStock() + " Amount: "
				+ order.getAmount() + " Price: " + order.getPrice());
	}

	public void AddBuyer(Order order) {
		MatchResult result = mapOfStocks.get(order.getStock()).addBuyer(order);
		if (result.getMatched()) {
			result.getBuyerOrder().setClosedAmount(
					result.getBuyerOrder().getAmount());
			sendToClients(result);
		}
		logger.info("Buyer Added" + order.getStock() + " Amount: "
				+ order.getAmount() + " Price: " + order.getPrice());

	}

	public void sendToClients(MatchResult result) {
		StockExchangeServer.listOfClientSession.get(
				result.getBuyerOrder().getOwner().getName()).sendResult(result);
		StockExchangeServer.listOfClientSession.get(
				result.getSellerOrder().getOwner().getName())
				.sendResult(result);
	}
}
